package com.jiangjiang.eshop.comment.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiangjiang.eshop.comment.biz.CommentInfoBiz;
import com.jiangjiang.eshop.comment.constant.ShowPictures;
import com.jiangjiang.eshop.comment.dto.*;
import com.jiangjiang.eshop.comment.service.CommentAggregateService;
import com.jiangjiang.eshop.comment.service.CommentPictureService;
import com.jiangjiang.eshop.membership.service.MembershipService;
import com.jiangjiang.eshop.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @ClassName CommentController
 * @Description TODO
 * @Author jhw
 * @Date 2021/5/17 21:28
 * @Version 1.0
 **/
@Slf4j
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentInfoBiz commentInfoBiz;
    @Autowired
    private CommentPictureService commentPictureService;
    @Autowired
    private CommentAggregateService commentAggregateService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MembershipService membershipService;

    /**
     * 评论列表分页查询
     * @param dto 评论分页查询DTO
     * @return 评论分页数据
     */
    @PostMapping("/queryForPage")
    public Page<CommentInfoDTO> queryForPage(@RequestBody CommentPageQueryDTO dto) {
        try {
            return commentInfoBiz.queryForPage(dto);
        } catch (Exception e) {
            log.warn("CommentController queryForPage error",e);
        }
        return null;
    }

    /**
     * 根据id查询评论详情
     * @param id 评论id
     * @return 评论详情数据
     */
    @GetMapping("/{id}")
    public CommentDetailDTO queryById(@PathVariable("id")Long id){
        try {
            return commentInfoBiz.queryById(id);
        }catch (Exception e){
            log.warn("CommentController queryById error",e);
        }
        return null;
    }

    /**
     * 新增评论信息
     *
     * @param commentInfoDTO
     * @param files
     * @return
     */
    @PostMapping("/publish")
    public Boolean publishComment(CommentInfoDTO commentInfoDTO, MultipartFile[] files, HttpServletRequest request) {
        try {

            // 1. 保存评论信息
            commentInfoDTO.setShowPictures(isShowPictures(files));
            commentInfoBiz.saveManualPublishedCommentInfo(commentInfoDTO);

            // 2. 上传评论晒图图片
            String appBasePath = request.getSession().getServletContext().getRealPath("/");
            commentPictureService.saveCommentPicture(appBasePath, commentInfoDTO.getId(), files);

            // 3. 更新评论聚合数据（没有聚合数据则新增一条）
            commentAggregateService.saveOrUpdate(commentInfoDTO);

            // 4. 通知订单中心已经发表评论
            orderService.informPublishCommentEvent(commentInfoDTO.getOrderInfoId());

            // 5. 通知会员中心用户已经发表评论
            membershipService.informPublishCommentEvent(
                    commentInfoDTO.getUserAccountId(),
                    ShowPictures.YES.equals(isShowPictures(files))
            );

        } catch (Exception e) {
            log.warn("CommentController publishComment error", e);
            return Boolean.FALSE;
        }

        return Boolean.TRUE;
    }

    /**
     * 判断是否上传了图片
     *
     * @param files
     * @return
     */
    private Integer isShowPictures(MultipartFile[] files) {
        Integer showPictures = ShowPictures.NO;
        if (files != null && files.length > 0) {
            for (MultipartFile file : files) {
                if (Objects.nonNull(file)) {
                    showPictures = ShowPictures.YES;
                    break;
                }
            }
        }
        return showPictures;
    }

    /**
     * 评论审核
     * @param id 评论id
     * @param approved 审核评论的状态
     * @return 处理结果
     */
    @GetMapping("/approve/{id}")
    public Boolean approve(@PathVariable("id") Long id,@RequestParam("approved")Integer approved){
        try {
          return commentInfoBiz.approveComment(id, approved);
        }catch (Exception e){
            log.warn("CommentController approve comment error",e);
            return Boolean.FALSE;
        }
    }

    /**
     * 评论删除
     * @param id 评论id
     * @return 处理结果
     */
    @GetMapping("/delete/{id}")
    public Boolean deleteComment(@PathVariable("id") Long id){
        try {
            return commentInfoBiz.deleteComment(id);
        }catch (Exception e){
            log.warn("CommentController delete comment error",e);
            return Boolean.FALSE;
        }
    }

    /**
     * 获取评论前台展示分页列表
     *
     * @param dto 入参
     * @return 查询结果
     */
    @GetMapping("/queryCommentShowForPage")
    public CommentShowDTO queryCommentShow(@RequestBody CommentPageQueryDTO dto) {
        try {
           return  commentInfoBiz.queryCommentShow(dto);
        }catch (Exception e){
            log.error("queryCommentShow error",e);
        }
        return null;
    }
}
